package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * ClassName: SimpleRedisLock
 * Package: com.hmdp.utils
 * Description:
 *
 * @Author: 葛龙
 * @Create 2025/3/23 16:14
 * @Version 1.0
 */
public class SimpleRedisLock implements Ilock {

    private StringRedisTemplate redisTemplate;
    private String name;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name){//利用构造器对全局变量进行赋值
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true);

    /**
     *获取锁
     * @param timeoutSec 锁超时时间，过了时间自动释放锁
     * @return
     */
    @Override
    public boolean tryLock(Long timeoutSec) {  //key要包含用户ID，value要包含线程的ID

        String id = ID_PREFIX + Thread.currentThread().getId();
        final Boolean setIfAbsent = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, id, timeoutSec, TimeUnit.SECONDS);//key必须包含用户ID，保证一人一单
        return setIfAbsent;
    }

    /**
     * 释放锁
     */
    @Override
    public void unlock() { //释放锁

        final String id = redisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (id.equals(ID_PREFIX + Thread.currentThread().getId())){ //判断当前线程ID和redis缓存的线程ID
            redisTemplate.delete(KEY_PREFIX + name);
        }

    }
}
